﻿/*
 * @author: wizardc
 */

using System;
using UnityEngine;
using UnityEngine.UI;

namespace Dou.UI
{
    /// <summary>
    /// 屏幕尺寸适配
    /// 当屏幕的高宽比发生改变时，自动判定是适配高度还是宽度
    /// </summary>
    [ExecuteInEditMode]
    public class CanvasScaleAdaptor : MonoBehaviour
    {
        private CanvasScaler _canvasScaler;
        // 设计尺寸的宽高比
        private float _designerAspectRatio;

        private void Start()
        {
            _canvasScaler = GetComponent<CanvasScaler>();
            if (_canvasScaler == null)
            {
                throw new Exception("没有找到CanvasScaler组件");
            }
            if (_canvasScaler.uiScaleMode != CanvasScaler.ScaleMode.ScaleWithScreenSize)
            {
                throw new Exception("CanvasScaler组件缩放模式必须是ScaleWithScreenSize");
            }
            _designerAspectRatio = _canvasScaler.referenceResolution.x / _canvasScaler.referenceResolution.y;
            Adjust();
        }

        /// <summary>
        /// 手动校正适配高度还是宽度
        /// </summary>
        public void Adjust()
        {
            var aspectRatio = (float) Screen.width / (float) Screen.height;
            _canvasScaler.matchWidthOrHeight = aspectRatio > _designerAspectRatio ? 1 : 0;
        }

#if UNITY_EDITOR
        private void LateUpdate()
        {
            Adjust();
        }
#endif
    }
}
